#!/bin/bash
#
# 添加学校脚本 2016-12-28
# 必须在master上执行
# 需要先修改好模板文件
# 1、serverAddress
# 2、mysql密码
#
. /usr/local/bin/logger
if [ ! -n "${1}" ] || [ ! -n "${2}" ] || [ ! -n "${3}" ]; then
        logger error "param error！！schoolCode & schoolName & sections  are required. eg：sh addSchool.sh BXFS001 博校附属中学 123" 
        exit
fi

test ! -d "/var/nas/yaml/school" && logger error "Error! model dir not found!"  && exit || logger "dir validate ok." 
time="$(date +%Y"-"%m"-"%d"_"%k":"%M":"%S)"
schoolCode=$1
schoolName=$2
sections=$3
schoolCodeLower=`echo $schoolCode | tr '[A-Z]' '[a-z]'`
schoolCodeUpper=$schoolCode

#dockerRegistry=`cat /usr/local/etc/registry`
#dockerRegistry=`cat /usr/local/etc/registry`
#if [ -z "$dockerRegistry" ]; then
#	logger error "Error! dockerRegistry setup error."
#	exit
#fi

#cluster ip
serverAddress="{set ip}"
becRootPassword="{set password}"
test "$serverAddress" == '{set ip}' && logger error "error！！{set ip} is error！！" && exit
test "$becRootPassword" == '{set password}' && logger error "error！！{set password} is error！！" && exit
schoolNameUnicode=`/usr/local/bin/convert2unicode $schoolName`
schoolNameUnicodeParam=`echo $schoolNameUnicode | sed "s/\\\\u/\\\\\\\\u/g"`
test -z "$schoolNameUnicodeParam" && logger error "Error! schoolNameUnicodeParam is null." && exit -1
#随机数字schoolkey
schoolKey=`cat /proc/sys/kernel/random/uuid | cksum | cut -f1 -d" "`
globalBXIKey=`cat /proc/sys/kernel/random/uuid`
userEncryptkey=`cat /proc/sys/kernel/random/uuid | tr '[a-z]' '[A-Z]' | sed "s/-//g"`
serverInnerAddress=`kubectl get svc | grep nginx | awk '{print $3}'`
test -z "$serverInnerAddress" && logger error "Error! serverInnerAddress not found. please check svc nginx."
logger "$time begin to create school : $schoolName."
logger "params: $serverAddress,$serverInnerAddress, $schoolNameUnicodeParam, $schoolCode, $schoolKey, $sections, $globalBXIKey, $userEncryptkey" 
logger "copy files..." 
# cp config & model files
/usr/local/bin/addSchool $serverAddress $serverInnerAddress $schoolNameUnicodeParam $schoolCode $schoolKey $globalBXIKey $userEncryptkey
if [ $? != 0 ]; then
	logger error "Error! cp config fils error."
	exit -1
fi
#cp kube obj files
cp -r /var/nas/yaml/school /var/nas/yaml/$schoolCode
test ! -d "/var/nas/yaml/$schoolCode" && logger error "/var/nas/yaml/$schoolCode not found!"  && exit -1
sed -i "s/{schoolCodeUpper}/$schoolCodeUpper/g" /var/nas/yaml/$schoolCode/*
sed -i "s/{schoolCodeLower}/$schoolCodeLower/g" /var/nas/yaml/$schoolCode/*
sed -i "s/{schoolName}/$schoolName/g" /var/nas/yaml/$schoolCode/rc-*.json
#sed -i "s/{dockerRegistry}/$dockerRegistry/g" /var/nas/yaml/$schoolCode/rc-*.json

#6.svc
logger "create svc..."
kubectl create -f /var/nas/yaml/$schoolCode/svc-app.json
kubectl create -f /var/nas/yaml/$schoolCode/svc-mysql.json
#1.create pv app
logger "create pv & pvc"
kubectl create -f /var/nas/yaml/$schoolCode/pv-app.json
sleep 1
kubectl create -f /var/nas/yaml/$schoolCode/pvc-app.json
#暂停一秒，防止pvc注册失败
sleep 1
#2.pvc
kubectl create -f /var/nas/yaml/$schoolCode/pv-mysql.json
sleep 1
kubectl create -f /var/nas/yaml/$schoolCode/pvc-mysql.json
sleep 1
#3.mysql
# select node
logger "select node..."
readyNodes=`kubectl get node | grep Ready | awk '{print $1}'`
test -z "$readyNodes" && logger error "Error! kubernetes has no Ready node!" && exit -1
#available
memoryAvailable=0
nodeSelector=null
for readyNode in $readyNodes; do
	test "$nodeSelector" == 'null' && nodeSelector=$readyNode
	logger "get memoryAvailable $readyNode..."
	memoryThis=`ssh root@$readyNode free | grep Mem | awk '{print $7}'`
	logger "$memoryThis"
	test "$memoryThis" -gt $memoryAvailable && memoryAvailable=$memoryThis && nodeSelector=$readyNode
done
test -z "$nodeSelector" && logger error "Error! mysql nodeSelector is null!" && exit -1
logger "nodeSelector : $nodeSelector, memoryAvailable is $memoryAvailable"

sed -i "s/{nodeSelector}/$nodeSelector/g" /var/nas/yaml/$schoolCode/rc-mysql.json
kubectl create -f /var/nas/yaml/$schoolCode/rc-mysql.json
#4.init-data
logger "starting mysql..."
while [ true ]; do
	mysqlPod=`kubectl get pod | grep $schoolCodeLower-mysql-m`
	mysqlPodStatus=`echo $mysqlPod | awk '{print $3}'`
	mysqlPodName=`echo $mysqlPod | awk '{print $1}'`
	if [ ! -z $mysqlPodName ]; then
		if [ 'Running' == "$mysqlPodStatus" ]; then
			logger "mysql $mysqlPodName started."
			while [ true ]; do
				testResult=`kubectl exec $mysqlPodName /bin/bash /usr/local/data/test-service.sh bxn500`
				if [ 'SUCCESS' == "$testResult" ]; then
					#init data
					logger "mysql service is ok, init data..."
					#rootPassword,schoolCode,version,section,(modules)
					kubectl exec $mysqlPodName /bin/bash  /usr/local/data/init.sh bxn500 $schoolCode 6.2.2 $sections bxn-timetable,bxn-office
					break
				else
					logger "mysql service is not ok.[$testResult]"
				fi
				sleep 5
			done
			break
		else
			logger "mysql $mysqlPodName starting... [$mysqlPodStatus]"
		fi
	fi
	#等待3秒
	sleep 5 
done
#5.tomcat
logger "starting tomcat..."
exit 0
kubectl create -f /var/nas/yaml/$schoolCode/rc-app.json

#创建bec端学校数据
rm -f /tmp/*.sql
logger "add admin user to bec."
cp /var/nas/data/init_becuser.sql /tmp/init_becuser_$schoolCodeLower.sql
sed -i "s/{schoolCode}/$schoolCode/g" /tmp/init_becuser_$schoolCodeLower.sql
sed -i "s/{schoolName}/$schoolName/g" /tmp/init_becuser_$schoolCodeLower.sql
mysql -uroot -p"$becRootPassword" < /tmp/init_becuser_$schoolCodeLower.sql


#添加bec配置文件
echo "$schoolCode=$schoolNameUnicode http://$serverInnerAddress true replaceToAreaNameUnicode" >> /usr/bx_app/config/bxnSchool.properties
echo "$schoolCode=$schoolKey" >> /usr/bx_app/config/ibcKey.properties

#添加becsso和bec的cluster，json
becLoginPage="/usr/bx_app/program/bec-sso/webapps/sso/WEB-INF/view/jsp/default/ui/casLoginView.jsp"
option="<option value=\"$schoolCode\">$schoolName</option>"
optionLine=`grep -n '<option' $becLoginPage | awk -F ':' '{print $1}'`
optionLine=`echo $optionLine |  awk -F ' ' '{print $NF}'`
sed -i "$optionLine a $option" $becLoginPage

becCluster="/var/nas/nginx/cluster.json"
schoolsLine=`grep -n '"schools": \[' $becCluster | awk -F ':' '{print $1}'`
schoolItem="{ \"ibcCode\": \"$schoolCode\", \"name\": \"$schoolName\", \"address\": \"http://$serverAddress\", \"innerAddress\": \"http://$serverInnerAddress\", \"cloudDeploy\": true, \"ssoProxy\": true, \"district\": \"上海市闵行区\", \"districtCode\": \"shq01\", \"status\": \"active\" },"
sed -i "$schoolsLine a $schoolItem" $becCluster

logger "addSchool $schoolName end."
